const state = {
  editing: {
    index: -1,
    title: '',
  },
  // list 存放的是实时显示的值，筛选条件变更后，它也会跟着变
  // original 存放的是原始的数据，不会通过改变筛选条件而发生变化
  original: [
    { title: '言叶之庭', isCompleted: true },
    { title: '哈尔的移动城堡', isCompleted: true },
    { title: '萤火之森', isCompleted: false },
    { title: '紫罗兰的永恒花园', isCompleted: false },
  ],
  msg: 'hello',
  list: [],
  displayType: 'all',
};

const getters = {
  list: state => {
    switch (state.displayType) {
      case 'all': {
        return state.original;
      }
      case 'active': {
        return state.original.filter(todo => !todo.isCompleted);
      }
      case 'completed': {
        return state.original.filter(todo => !todo.isCompleted);
      }
    }
  },
  original: state => state.original,
  msg: state => state.msg,
  editing: state => state.editing,
  displayType: state => state.displayType,
};

const mutations = {
  CREATE_TODO: (state, title) => {
    state.original.push({
      title,
      isCompleted: false,
    });
  },

  REMOVE_TODO: (state, index) => {
    state.original.splice(index, 1); //删除传过来的index，删除长度为1
    state.list = state.original;
  },

  EDIT_TODO: (state, todoIndex) => {
    state.editing.index = todoIndex;
    state.editing.title = state.original[todoIndex].title;
  },
  CANCELEDIT_TODO: state => {
    state.editing.index = -1;
  },
  REMOVEDONE_TODO: state => {
    for (let i = state.original.length - 1; i >= 0; i--) {
      if (state.original[i].isCompleted) {
        state.original.splice(i, 1);
      }
    }
  },
  DISPLAY_TYPE: (state, displayType) => {
    state.displayType = displayType;
  },
};
const actions = {
  createTodo({ commit }, title) {
    commit('CREATE_TODO', title);
  },
  removeTodo({ commit }, index) {
    commit('REMOVE_TODO', index);
  },
  editTodo({ commit }, todoIndex) {
    commit('EDIT_TODO', todoIndex);
  },
  canceleditTodo({ commit }) {
    commit('CANCELEDIT_TODO');
  },
  removedoneTodo({ commit }) {
    commit('REMOVEDONE_TODO');
  },
  displayType: ({ commit }, displayType) => {
    commit('DISPLAY_TYPE', displayType);
  },
};
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
